/**
 * Created by wenpeng on 2016/12/12.
 */
$(function () {
    'use strict';
    ImporInfor();
    var uuidLocal = Cookie.getCookie()['uuid'],
        imgList = {},
        Img = false,
        authen = '',
        name = '',
        state = '/myhome/shop/getMyAuthenticateStatus',
        source = getQueryString('personal'),
        allPlaceApi = '/goodsLocus/searchAllGoodsLocus';
    $('#back').on('click', function () {
        window.history.back();
    })
    if(!uuidLocal){                                         // 没有登陆直接跳转
        layer.open({
            content: '您还没有登录，请先登录！'
            ,btn: ['去登录', '去首页']
            ,shadeClose:false
            ,yes: function(index){
                window.location.href = 'login.html';
                layer.close(index);
            }
            ,no: function (index) {
                window.location.href = 'index.html';
                layer.close(index);
            }
        });
        return;
    };
    // 个人认证企业认证区分
    if(source){
        authen = '/myhome/userident/authenticate'   // 个人认证
        $('.header-tab h5').text('个人认证')
        document.title = '找牛网-个人认证'
        name = '实名认证'
        $('.enterprise').hide();
    }else {
        authen = '/myhome/enterpriseident/authenticate'   // 企业认证
        $('.header-tab h5').text('企业认证')
        document.title = '找牛网-企业认证'
        $('.enterprise').show();
        name = '企业认证'
        warehouse();
    }
    var end = '<img src="img/shop/icon-shtg.png" alt=""> <p style="margin-bottom: 35px">恭喜您，您的'+name+'已通过！</p> <a href="index.html" class="btn">返回首页</a>',
        ing = '<img src="img/shop/icon-shz.png" alt=""> <p style="margin-bottom: 35px">您的资料正在审核中，请耐心等待!</p> <a href="index.html" class="btn">返回首页</a>',
        err = function (obj,source) {
            source = source || '';
            return '<img src="img/shop/icon-shsbb.png   " alt=""> <p style="color:#999; text-align:left;">非常抱歉，您未能通过认证审核，请检查提交的资料是否存在以下问题：</p><p style="text-align:left;margin-bottom: 35px;">'+obj+'</p><a href="index.html" class="btn">返回首页</a><a style=" margin-left: 20%;" href="javascript:;" id="anew" class="btn">重新提交资料</a>'
        };
        $.ajax({
        url:host + state,
        type:"post",
        data: Infornation,
        success:function (data) {
        // 认证状态显示
        if(data.success) {
            var data = data.data,
                what = data.authenticationStatus,
                current = data.auditStatus,
                user = data.userIdentity,
                jroll = null;
            console.log(data)
            // 没有数据则初始状态
            if (!data) {
                $('.currentstate span').eq(0).addClass('currentState')
                $('#information').show();
                keyboard();
                return;
                // 首先判断是否个人 企业一起认证
            } else if ((what === 1 && current === 1 && source) || (what === 2 && current === 1 && !source) || (what === 3 && current === 1 && source) || (what === 3 && current === 1 && !source)) {
                $('.currentstate span').eq(1).addClass('currentState')
                $('#state').html(ing).show();
                return;
            } else if ((what === 1 && current === 2 && source) || (what === 2 && source) || (what === 2 && current === 2 && !source) || (what === 3 && current === 2 && source) || (what === 3 && current === 2 && !source)) {
                $('.currentstate span').eq(2).addClass('currentState')
                $('#state').html(end).show();
                return;
            } else if ((what === 1 && current === 3 && source) || (what === 2 && current === 3 && !source) || (what === 3 && current === 3)) {
                fail();
                return;
            } else if ((what === 1 && current === 2 && !source) || (what === 1 && current === 3 && !source)) {
                if(what === 1 && current === 3 && !source){
                    $('.currentstate span').eq(0).addClass('currentState')
                    $('#information').show();
                    keyboard()
                    return;
                }
                $('.identityName').val(user.identityName).attr('readonly', true)
                $('.indetityNumber').val(user.indetityNumber).attr('readonly', true)
                $('.uploadImg').eq(1).hide(300, function () {
                    $(this).parent('.img-container').prepend($('<span><div><img src="' + user.pictureFront + '" alt=""></div></span>'))
                })

                $('.uploadImg').eq(2).hide(300, function () {
                    $(this).parent('.img-container').prepend($('<span><div><img src="' + user.pictureBack + '" alt=""></div></span>'))
                })
                $('.uploadImg').eq(3).hide(300, function () {
                    $(this).parent('.img-container').prepend($('<span><div><img src="' + user.handheldPhoto + '" alt=""></div></span>'))
                })
                $('.currentstate span').eq(0).addClass('currentState')
                $('#information').show();
                imgList.pictureFront = user.pictureFront;
                imgList.pictureBack = user.pictureBack;
                imgList.handheldPhoto = user.handheldPhoto;
                keyboard()
                return;
            } else if ((what === 1 && current === 1 && !source)) {
                layer.open({
                    content: '个人认证过程中无法进行企业认证，请确定个人认证已成功或者失败'
                    , btn: ['去首页', '查看状态']
                    , shadeClose: false
                    , yes: function (index) {
                        window.location.href = 'index.html';
                        layer.close(index);
                    }
                    , no: function (index) {
                        window.location.href = 'authentication.html?personal=true';
                        layer.close(index);
                    }
                });
                return;
            } else {
                //    没有了
            }
        }else {
            layer.open({
                content: '服务器出错！是否刷新？刷新失败后请过会重试；'
                , btn: ['去首页', '刷新']
                , shadeClose: false
                , yes: function (index) {
                    window.location.href = 'index.html';
                    layer.close(index);
                }
                , no: function (index) {
                   window.location.reload()
                    layer.close(index);
                }
            });
        }
            function fail() {
                $('.currentstate span').eq(2).text('3.认证失败').css('color','red')
                $('#state').html(err(data.auditProfile, source)).show();
                $('#anew').on('click', function () {
                    $('.currentstate span').eq(2).text('3.认证成功').css('color','#4d4d4d')
                    $('.currentstate span').eq(0).addClass('currentState')
                    $('#state').hide();
                    var flag = data.authenticationStatus === 2? true:false;
                    var hid = flag?'hidden':'';
                    $('.identityName').val(user.identityName).attr('readonly',flag)
                    $('.indetityNumber').val(user.indetityNumber).attr('readonly',flag)
                    $('.uploadImg').eq(1).hide(300, function () {
                        $(this).parent('.img-container').prepend($('<span><i class="'+hid+'" data-img="pictureFront"></i><div><img src="'+user.pictureFront+'" alt=""></div></span>'))
                    })

                    $('.uploadImg').eq(2).hide(300, function () {
                        $(this).parent('.img-container').prepend($('<span><i class="'+hid+'" data-img="pictureBack"></i><div><img src="'+user.pictureBack+'" alt=""></div></span>'))
                    })
                    $('.uploadImg').eq(3).hide(300, function () {
                        $(this).parent('.img-container').prepend($('<span><i class="'+hid+'" data-img="handheldPhoto"></i><div><img src="'+user.handheldPhoto+'" alt=""></div></span>'))
                    })
                    imgList.pictureFront = user.pictureFront;
                    imgList.pictureBack = user.pictureBack;
                    imgList.handheldPhoto = user.handheldPhoto;
                    data.businessType === 1?$('input[name="businessType"]').eq(0).attr('checked', true):data.businessType === 2?$('input[name="businessType"]').eq(0).attr('checked', true):$('input[name="businessType"]').attr('checked', true);


                    $('.currentstate span').eq(0).addClass('currentState')
                    if(!source){
                        $('.uploadImg').eq(0).hide(300, function () {
                            $(this).parent('.img-container').prepend($('<span><i data-img="businessLicensePic"></i><div><img src="'+data.enterpriseIdentity.businessLicensePic+'" alt=""></div></span>'))
                        })
                        var city =data.enterpriseIdentity.address.split('市')[0] + '市',
                            str = data.enterpriseIdentity.address.split('市')[1];
                        imgList.businessLicensePic = data.enterpriseIdentity.businessLicensePic;
                        $('input[name="enterpriseName"]').val(data.enterpriseIdentity.enterpriseName);
                        $('input[name="address"]').val(city);
                        $('input[name="street"]').val(str);
                        $('input[name="phone"]').val(data.enterpriseIdentity.phone);
                    }
                    $('#information').show();
                    keyboard();
                    jroll.refresh()
                })
            }
            // 输入框键盘遮挡问题
            function keyboard() {
                jroll && jroll.destroy && jroll.destroy();
                jroll = new JRoll("#information",{
                    scrollBarY: true,
                    scrollBarFade: true
                });
                jroll.fixedinput(150); //使该JRoll对象里的input/textarea在focus时能自动上移到可见位置
            }
        }
    })

// 监听 change 事件
    $('input[type="file"]').on('change', function () {
        var _this = this,
            file = Array.prototype.slice.call(this.files)[0],
            index = $(this).index('input[type="file"]'),
            fileName = this.name;
        if (!this.files.length){
            $('.uploadImg').eq(index).show()
            return;
        }else{
            $('.uploadImg').eq(index).hide()
        }
        lrz(file,{
            quality: 0.5,
            fieldName: 'imageFile',
            width: 880
        })
            .then(function (rst) {
                // 处理成功会执行
                imgList[fileName] = rst;
                // setTimeout(function () {
                    $('<span><i data-img="'+fileName+'"></i><div><img src="'+rst.base64+'" alt=""></div></span>').insertBefore($(_this).parents('.uploadImg').siblings('.examples'));
                    $('.img-container>span').css('height',$('.examples').eq(1).height());
                // },100)
            })
            .catch(function (err) {
                // 处理失败会执行
                console.log(err)
            })
            .always(function () {
                // 不管是成功失败，都会执行
            });
    })

    // 删除图片
    $('.img-container').on('click', function (e) {
        var target = e.target,
            imgUrl = e.target.src?e.target.src:'';
        if (target.nodeName==="IMG") {
            $('#imgbox').empty().append('<div><i></i><img src='+imgUrl+'></div>').show()
        }else if(target.nodeName==="I"){
            layer.open({
                content: '确认删除照片吗？'
                ,btn: ['取消', '确定']
                ,style: 'color:#333;'
                ,skin: 'footer'
                ,no: function(){
                    var count;
                    layer.closeAll();
                    count = $(target).data('img');
                    imgList[count] = null;
                    $(target).parent('span').fadeOut(500,function () {
                        $('.'+count).parents('.uploadImg').show();
                        $(this).remove()
                    })
                }
            });


        }
    });

    $('#imgbox').click(function () {
        $(this).hide();
    });




    $('#information button').on('click', function () {
        var numArr = ['企业名称','业务种类','公司地址','真实姓名','联系电话','身份证号','营业执照','身份证正面照', '身份证背面照','手持身份证照']
        // 必填项验证
        var enterpriseName = $('input[name="enterpriseName"]').val().trim(), // 企业名字
            businessType = 0,                                                // 企业业务
            address = $('input[name="address"]').val().trim(),              // 企业地址
            street = $('input[name="street"]').val().trim(),              // 企业街道
            identityName = $('input[name="identityName"]').val().trim(),    // 申请人姓名
            phone = $('input[name="phone"]').val().trim(),                  // 电话
            indetityNumber = $('input[name="indetityNumber"]').val().trim(),// 身份证号码
            parames = '',
            index = 0,
            current;
        $('input[name="businessType"]:checked').each(function () {
            businessType += Number($(this).val());
        });
        if(!identityName){ lay.msg(numArr[3] + '不能为空'); return;}
        parames += 'identityName=' + identityName;
        if(!businessType){ lay.msg(numArr[1] + '不能为空'); return;}
        parames += '&businessType=' + businessType;
        if(!source){
            current = 4;
            if(!enterpriseName){ lay.msg(numArr[0] + '不能为空'); return;}
            parames += '&enterpriseName=' + enterpriseName;
            if(!address){ lay.msg(numArr[2] + '不能为空'); return;}
            parames += '&address=' + address + street;
            if(!phone || !( /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/.test(phone))){ lay.msg(numArr[4] + '格式不正确或不能为空'); return;}
            parames += '&phone=' + phone;
            if(!imgList['businessLicensePic']){lay.msg('营业执照不能为空');return;}

        }else {
            current = 3
        }
        if(!indetityNumber || !(/(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/.test(indetityNumber))){ lay.msg(numArr[5] + '格式不正确或不能为空'); return;}
        parames += '&indetityNumber=' + indetityNumber;
        // if(!imgList['pictureBack'] || !imgList['pictureFront'] || !imgList['handheldPhoto']){
        //     lay.msg('全部照片不能为空')
        //     return;
        // }
        if(!imgList['pictureFront']){lay.msg(numArr[7]+'不能为空');return;}
        if(!imgList['pictureBack']){lay.msg(numArr[8]+'不能为空');return;}
        if(!imgList['handheldPhoto']){lay.msg(numArr[9]+'不能为空');return;}
        parames +='&'+ Infornation;
        for(var key in imgList){
            if(typeof imgList[key] == 'string'){
                parames += '&'+key+'='+ imgList[key].split('/')[5];
                current--
            }
        }
       if(current){
           for(var key in imgList){
               if(typeof imgList[key] !== 'string'){
                   (function (key,imgList) {
                       upImg(imgList[key],function (data) {
                           index++;
                           parames += '&'+key+'='+ data.message;
                           if(index === current){
                               $.ajax({
                                   url:host + authen,
                                   type:"post",
                                   data: parames,
                                   success: function (data) {
                                       if(data.success){
                                           layer.closeAll();
                                           $('#information').hide();
                                           $('#state').html(ing).show();
                                           $('.currentstate span').removeClass('currentState').eq(1).addClass('currentState')
                                       }
                                   },
                                   error: function () {
                                       layer.open({
                                           content: '提交信息失败；请刷新后重试'
                                           ,btn: ['重试', '取消']
                                           ,shadeClose:false
                                           ,yes: function(index){
                                               window.location.reload();
                                               layer.close(index);
                                           }
                                           ,no: function (index) {
                                               layer.closeAll();
                                           }
                                       });
                                   }
                               })
                           }
                       })
                   })(key,imgList)
               }
           }
       }else {
           $.ajax({
               url:host + authen,
               type:"post",
               data: parames,
               success: function (data) {
                   if(data.success){
                       layer.closeAll();
                       $('#information').hide();
                       $('#state').html(ing).show();
                       $('.currentstate span').removeClass('currentState').eq(1).addClass('currentState')
                   }else {
                       layer.open({
                           content: '提交信息失败；请刷新后重试'
                           ,btn: ['重试', '取消']
                           ,shadeClose:false
                           ,yes: function(index){
                               window.location.reload();
                               layer.close(index);
                           }
                           ,no: function (index) {
                               layer.closeAll();
                           }
                       });
                   }
               },
               error: function () {
                   layer.open({
                       content: '提交信息失败；请刷新后重试'
                       ,btn: ['重试', '取消']
                       ,shadeClose:false
                       ,yes: function(index){
                           window.location.reload();
                           layer.close(index);
                       }
                       ,no: function (index) {
                           layer.closeAll();
                       }
                   });
               }
           })
       }

        

    })
    function upImg(obj,fn) {
        $.ajax({
            url:hostImgUpload + '?&isAddWatermark=false',
            type:"post",
            data:obj.formData,
            processData:false,// 不要处理发送的数据
            contentType:false,// 不要设置请求头
            dataType:'json',
            beforeSend:function () {
                layer.open({
                    type: 2
                    ,content: '资料上传中...'
                    ,shadeClose:false
                });
            },
            success:function(data){
                fn(data)
            },
            error:function(e){
                // lay.msg('上传资料失败；请刷新后重试；')
                // setTimeout(function () {
                //     window.location.reload();
                // },500)
                return;
                // window.clearInterval(timer);
            }
        });
    }
//   所在地
    function warehouse() {
        $('.row').eq(5).find('.col-xs-1').on('click', function () {
            if($('.searchItim', '.item-warehouse')[0]){
                $('.item-warehouse').removeClass('hidden')
                return
            }
            // 所在地
            $.getJSON(host + allPlaceApi, function (data) {
                var htmlStr = '<ul class="searchItim"><li class="check" data-id="0"><a href="javascript:;">不限</a> </li>',
                    contentBox = $('.item-warehouse .content1'),
                    parseData = function (data) {
                        for(var i = 0; i < data.length; i++){
                            if(data[i].childrenList.length){
                                htmlStr += '<li><a href="javascript:;">'+data[i].goodsLocusName+'</a> <ul style="display: none;">'
                                parseData(data[i].childrenList)
                                htmlStr += '</ul></li>'
                            }else {
                                htmlStr += '<li data-id='+data[i].id+' class="check"><a href="#">'+data[i].goodsLocusName+'</a></li>'
                            }
                        }
                    };
                if (data.success) {
                    $('.item-warehouse').removeClass('hidden')
                    parseData(data.data)
                    htmlStr += '</ul>'
                    contentBox.append(htmlStr)

                    // // 手风琴效果
                    $('.searchItim', contentBox).accordion({
                        //accordion: true,
                        speed: 100,
                        closedSign: '[+]',
                        openedSign: '[-]'
                    })
                    // 点击事件
                    $('.check', contentBox).on('touchstart', function () {
                        $(this).find('a').css('backgroundColor','#eee')
                    })
                    $('.check', contentBox).on('touchend', function () {
                        $(this).find('a').css('backgroundColor','transparent')
                    })
                    $('.check', contentBox).on('click', function () {
                        $('input[name="street"]').val('')
                        $('.check', contentBox).removeClass('checked');
                        $(this).addClass('checked')
                        $(this).find('a').css('backgroundColor','transparent')
                        console.log();
                        $(".address").val($(this).parents('li').eq(0).children('a').text().slice(0, -3)+'省'+$(this).text() + '市');
                        $('.item-warehouse').addClass('hidden')
                    })
                } else {
                    console.log(data.message)
                }
            })
        })
        // 所在地取消按钮
        $('.item-warehouse button').on('click', function () {
            $('.item-warehouse').addClass('hidden')
        })
    }
})

